import datetime
import os
from time import sleep

import yaml
from selenium.webdriver.common.by import By

from qiyeweixin_testing.page_object.base_page import BasePage
from qiyeweixin_testing.until.log_utils import logger

cookies_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'cookies.yml')


class LoginPage(BasePage):
    _BASE_URL = "https://work.weixin.qq.com/wework_admin/loginpage_wx"

    __JS_TIPS = (By.ID, "js_tips")

    def login(self):
        if not os.path.exists(cookies_path):
            self.driver.execute_script('alert("需要微信扫码登录！")')
            sleep(20)
            cookies = self.driver.get_cookies()
            write_time = datetime.datetime.now()
            cookies_dict = {
                "write_time": write_time,
                "cookies": cookies
            }
            with open(cookies_path, 'w', encoding='utf-8') as f:
                yaml.safe_dump(cookies_dict, f)

        with open(cookies_path, 'r', encoding='utf-8') as f:
            cookies_dict = yaml.safe_load(f)

        cookies = cookies_dict.get("cookies")
        write_time = cookies_dict.get("write_time")
        now = datetime.datetime.now()
        diff_day = (now - write_time).days
        ele_flag = None

        try:
            ele_flag = self.wait_until_element(self.__JS_TIPS)
        except Exception as e:
            logger.debug(e)
        finally:
            if diff_day >= 7 or ele_flag:
                os.remove(cookies_path)
                LoginPage(self.driver).login()

            for ck in cookies:
                self.driver.add_cookie(ck)

            self.driver.get(self._BASE_URL)

            from qiyeweixin_testing.page_object.home_page import HomePage
            return HomePage(self.driver)


if __name__ == "__main__":
    LoginPage().login()
